<template>
  <el-upload
    action="/api/file/picture"
    :file-list="fileList"
    class="upload-demo"
    multiple
    :limit="9"
    :before-upload="beforeUpload"
    :http-request="customUpload"
    :on-success="handleSuccess"
    :on-error="handleError"
    :show-file-list="false"
    :drag="false"
    :disabled="loading"
  >
    <el-button type="primary" :loading="loading">{{ $t("pickPicture.选择图片") }}</el-button>
  </el-upload>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import axios from "axios";

const { t } = useI18n();
const fileList = ref([]);
const props = defineProps({});
const emit = defineEmits(["success", "error", "update:modelValue", "change"]);
const loading = ref(false)
// 上传前的校验
const beforeUpload = (file) => {
  
  // 检查文件类型
  const fileType = file.type;
  const acceptTypes = "image/jpeg,image/png,image/jpg,image/gif".split(",");
  const isAccept = acceptTypes.some((type) => {
    // 处理mime类型带通配符的情况，如image/*
    if (type.includes("*")) {
      const mainType = type.split("/")[0];
      return fileType.startsWith(mainType);
    }
    return type === fileType;
  });
  if (!isAccept) {
    ElMessage.error(
      t("uploadFile.文件格式不正确", { types: acceptTypes.join("/") })
    );
    return false;
  }
  // 检查文件大小
  const isLtSize = file.size / 1024 / 1024 < 5;
  if (!isLtSize) {
    ElMessage.error(t("uploadFile.文件大小不能超过", { size: 5 }));
    return false;
  }

  return true;
};

// 自定义上传方法
const customUpload = async (options) => {
  const { file, onProgress, onSuccess, onError } = options;
  // 创建 FormData 对象，添加文件和额外数据
  const formData = new FormData();
  formData.append("file", file);
  loading.value = true
  try {
    const token = Storage.get("token", true);
    const config = {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: token,
        "Accept-Language": "zh_CN",
      },
    };

    // 发送上传请求
    const response = await axios({
      method: "post",
      url: "/api/file/picture",
      data: formData,
      ...config,
    });

    // 获取响应数据
    const responseData = response.data;
    if (responseData.status === 200) {
      // onSuccess(responseData);
      return responseData;
    } else {
      onError({});
    }
  } catch (error) {
    // 上传失败
    onError(error);
    return Promise.reject(error);
  }
};

// 上传成功回调
const handleSuccess = (response, file, uploadFiles) => {
  loading.value = false
  ElMessage.success(t("uploadFile.上传成功"));
  // 更新文件url (从响应中获取)
  if (response) {
    const url = response.data.url || "";
    if (url) {
      file.url = url;
    }
  }
  if(uploadFiles.every(item => item.url)) {
    // 同步到父组件
    updateModelValue(uploadFiles);
    emit("success", response, file, uploadFiles);
  }
};

// 上传失败回调
const handleError = (error, file, uploadFiles) => {
  loading.value = false
  ElMessage.error(t("uploadFile.上传失败"));
  emit("error", error, file, uploadFiles);
  fileList.value = [];
};

// 更新modelValue的函数
const updateModelValue = (files) => {
  const valueToEmit = files.map((file) => {
    // 如果已有url，直接返回url
    if (file.url) {
      return { url: file.url, name: file.name };
    }
    // 如果是刚上传的文件，从响应中获取url
    else if (file.response) {
      const url = file.response.data.url;
      const name = file.response.data.filename || file.name;
      return { url, name };
    }
    // 回退方案
    return file;
  });
  const res = JSON.parse(JSON.stringify(valueToEmit));
  emit("update:modelValue", res);
  emit("change", res);
  fileList.value = [];
};
</script>
